package org.example.system.controller.system;

import com.baomidou.lock.annotation.Lock4j;
import lombok.RequiredArgsConstructor;
import org.example.common.core.constants.TenantConstants;
import org.example.common.core.domain.R;
import org.example.common.core.utils.page.Pager;
import org.example.common.core.validate.AddGroup;
import org.example.common.core.validate.EditGroup;
import org.example.common.datasource.utils.TenantHelper;
import org.example.common.excel.utils.ExcelUtil;
import org.example.common.log.annotation.OperatorLog;
import org.example.common.log.enums.BusinessType;
import org.example.common.security.annotation.PreAuthorize;
import org.example.common.security.annotation.PreRoleAuthorize;
import org.example.common.web.annotation.RepeatSubmit;
import org.example.system.domain.bo.SysTenantBo;
import org.example.system.domain.vo.SysTenantVo;
import org.example.system.service.ISysTenantService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;

/**
 * 租户管理
 *
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/tenant")
public class SysTenantController   {

    private final ISysTenantService tenantService;

    /**
     * 查询租户列表
     */
    @PreAuthorize(hasAnyPermi = {"system:tenant:list"},andRoles = TenantConstants.SUPER_ADMIN_ROLE_KEY)
    @PostMapping("/list")
    public Pager<SysTenantVo> list(@RequestBody Pager pageQuery) {
        return tenantService.queryPageList(pageQuery);
    }

    /**
     * 导出租户列表
     */
    @PreAuthorize(hasAnyPermi = {"system:tenant:export"},andRoles = TenantConstants.SUPER_ADMIN_ROLE_KEY)
    @OperatorLog(title = "租户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(@RequestBody Pager pageQuery, HttpServletResponse response) {
        List<SysTenantVo> list = tenantService.queryList(pageQuery);
        ExcelUtil.exportExcel(list, "租户", SysTenantVo.class, response);
    }

    /**
     * 获取租户详细信息
     *
     * @param id 主键
     */
    @PreAuthorize(hasAnyPermi = "system:tenant:query",andRoles = TenantConstants.SUPER_ADMIN_ROLE_KEY)
    @GetMapping("/{id}")
    public R<SysTenantVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(tenantService.queryById(id));
    }

    /**
     * 新增租户
     */
    @PreAuthorize(hasAnyPermi = "system:tenant:add",andRoles = TenantConstants.SUPER_ADMIN_ROLE_KEY)
    @OperatorLog(title = "租户", businessType = BusinessType.INSERT)
    @Lock4j
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody SysTenantBo bo) {
        if (!tenantService.checkCompanyNameUnique(bo)) {
            return R.fail("新增租户'" + bo.getCompanyName() + "'失败，企业名称已存在");
        }
        return R.toAjax(TenantHelper.ignore(() -> tenantService.insertByBo(bo)));
    }

    /**
     * 修改租户
     */
    @PreAuthorize(hasAnyPermi = "system:tenant:edit",andRoles = TenantConstants.SUPER_ADMIN_ROLE_KEY)
    @OperatorLog(title = "租户", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody SysTenantBo bo) {
        tenantService.checkTenantAllowed(bo.getTenantId());
        if (!tenantService.checkCompanyNameUnique(bo)) {
            return R.fail("修改租户'" + bo.getCompanyName() + "'失败，公司名称已存在");
        }
        return R.toAjax(tenantService.updateByBo(bo));
    }

    /**
     * 状态修改
     */
    @PreAuthorize(hasAnyPermi = "system:tenant:edit",andRoles = TenantConstants.SUPER_ADMIN_ROLE_KEY)
    @OperatorLog(title = "租户", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public R<Void> changeStatus(@RequestBody SysTenantBo bo) {
        tenantService.checkTenantAllowed(bo.getTenantId());
        return R.toAjax(tenantService.updateTenantStatus(bo));
    }

    /**
     * 删除租户
     *
     * @param ids 主键串
     */
    @PreAuthorize(hasAnyPermi = "system:tenant:remove",andRoles = TenantConstants.SUPER_ADMIN_ROLE_KEY)
    @OperatorLog(title = "租户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return R.toAjax(tenantService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 动态切换租户
     *
     * @param tenantId 租户ID
     */
    @PreRoleAuthorize(hasRole = TenantConstants.SUPER_ADMIN_ROLE_KEY)
    @GetMapping("/dynamic/{tenantId}")
    public R<Void> dynamicTenant(@NotBlank(message = "租户ID不能为空") @PathVariable String tenantId) {
        TenantHelper.setDynamic(tenantId);
        return R.ok();
    }

    /**
     * 清除动态租户
     */
    @PreRoleAuthorize(hasRole = TenantConstants.SUPER_ADMIN_ROLE_KEY)
    @GetMapping("/dynamic/clear")
    public R<Void> dynamicClear() {
        TenantHelper.clearDynamic();
        return R.ok();
    }


    /**
     * 同步租户套餐
     *
     * @param tenantId  租户id
     * @param packageId 套餐id
     */
    @PreAuthorize(hasAnyPermi = "system:tenant:edit",andRoles = TenantConstants.SUPER_ADMIN_ROLE_KEY)
    @OperatorLog(title = "租户", businessType = BusinessType.UPDATE)
    @GetMapping("/syncTenantPackage")
    public R<Void> syncTenantPackage(@NotBlank(message = "租户ID不能为空") String tenantId,
                                     @NotNull(message = "套餐ID不能为空") Long packageId) {
        return R.toAjax(TenantHelper.ignore(() -> tenantService.syncTenantPackage(tenantId, packageId)));
    }

}
